package com.kefu.call.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.basic.mapper.BasicRptMapper;
import com.kefu.basic.model.BasicRpt;
import com.kefu.basic.model.BasicRptCol;
import com.kefu.call.mapper.CallMakeCallMapper;
import com.kefu.call.model.CallMakeCall;
import com.kefu.call.vo.CallMakeCallVo.CallMakeCallRptVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Mr Y
 * @Date: 2021/12/02/14:57
 * @Description:
 */
@Slf4j
@Service
public class CallMakeCallService extends AbstractKefuService<CallMakeCall> {
    @Resource
    private BasicRptMapper basicRptMapper;
    @Resource
    private CallMakeCallMapper callMakeCallMapper;

    /**
     * 外呼纪录
     * @param search
     * @return
     */
    public Page<Map<String, Object>> callMakeCallRecord(CallMakeCallRptVo search) {
        Assert.isEmpty(search.getRptId(), "未选择方案");
        String rptId = search.getRptId();
        BasicRpt rpt = basicRptMapper.selectByPrimaryKey(rptId);
        Assert.isNull(rpt, "自定义字段已被删除!");
        String cols = rpt.getRptFields();
        Assert.isEmpty(cols, "未设置查询字段");
        List<BasicRptCol> basicRptCols = JSONUtil.parseArray(cols).toList(BasicRptCol.class);
        String sql = basicRptCols.stream().map(BasicRptCol::getCodeFunction).collect(Collectors.joining(","));
        Assert.isEmpty(sql, "未设置显示字段内容！");
        Page<Map<String, Object>> page = new Page<>(search.getPageNo(), search.getPageSize(), true);
        QueryWrapper<CallMakeCall> wrapper = Wrappers.query();
        wrapper.eq("Company", KefuContext.getTid());
        wrapper.eq(StrUtil.isNotBlank(search.getAgentId()), "CCAgent", search.getAgentId());
        wrapper.eq(Objects.nonNull(search.getAnswerStatus()), "answerStatus", search.getAnswerStatus());
        wrapper.like(StrUtil.isNotBlank(search.getCallerNumber()), "callerNumber", search.getCallerNumber());
        wrapper.like(StrUtil.isNotBlank(search.getCalleeNumber()), "calleeNumber", search.getCalleeNumber());
        wrapper.ge(Objects.nonNull(search.getMinTalkTime()), "talkTime", search.getMinTalkTime());
        wrapper.le(Objects.nonNull(search.getMaxTalkTime()), "talkTime", search.getMaxTalkTime());
        wrapper.ge(Objects.nonNull(search.getCallStartTime()), "TPRingTime",
                        Timestamp.valueOf(DateUtil.format(new Date(search.getCallStartTime()), "yyyy-MM-dd HH:mm:ss")));
        wrapper.le(Objects.nonNull(search.getCallEndTime()), "TPRingTime", Timestamp.valueOf(DateUtil.format(new Date(search.getCallEndTime()), "yyyy-MM-dd HH:mm:ss")));
        page.setTotal(callMakeCallMapper.selectCount(wrapper));
        wrapper.select(sql);
        wrapper.last("LIMIT " + search.getPageSize() + " OFFSET " + (search.getPageSize() * (search.getPageNo() - 1)));
        List<Map<String, Object>> mapList = callMakeCallMapper.selectMaps(wrapper);
        page.setRecords(mapList);
        return page;
    }

    /**
     * 导出外呼纪录
     * @param search
     * @return
     */
    public List<Object[]> callMakeCallRecordExport(CallMakeCallRptVo search) {
        Assert.isNull(search.getCallStartTime(), "未选择开始时间！");
        BasicRpt rpt = basicRptMapper.selectByPrimaryKey(search.getRptId());
        Assert.isNull(rpt, "自定义字段已被删除!");
        String rptFields = rpt.getRptFields();
        Assert.isEmpty(rptFields, "未设置显示字段");
        List<BasicRptCol> basicRptCols = JSONUtil.parseArray(rptFields).toList(BasicRptCol.class);
        search.setPageNo(1);
        search.setPageSize(50000);
        List<Map<String, Object>> records = callMakeCallRecord(search).getRecords();
        List<Object[]> exportList = new ArrayList<>();
        Object[] title = new Object[basicRptCols.size()];
        for (int i = 0; i < basicRptCols.size(); i++) {
            title[i] = msg(basicRptCols.get(i).getCodeName());
        }
        exportList.add(title);
        for (Map<String, Object> i : records) {
            Object[] row = new Object[basicRptCols.size()];
            for (int j = 0; j < basicRptCols.size(); j++) {
                Object cell = i.get(basicRptCols.get(j).getCodeId());
                row[j] = cell;
            }
            exportList.add(row);
        }
        return exportList;
    }
}
